package com.yxr.affairs;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.thoughtworks.xstream.XStream;
import com.yxr.affairs.api.Constans1;
import com.yxr.affairs.home.Data;
import com.yxr.affairs.home.Param1;
import com.yxr.affairs.home.Storeditem;
import com.yxr.affairs.base.BaseActivity1;
import com.yxr.affairs.utils.ToastUtil;
import com.yxr.affairs.utils.Utils;
import com.yxr.affairs.xtem.EncodeXstream;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.Context.MODE_PRIVATE;


public class InformActivity extends BaseActivity1 {


    @BindView(R.id.user_feedback_goback)
    ImageButton userFeedbackGoback;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rv_invest1)
    ExpandableListView rvInvest1;

    private   String Honst;
    private  String  time;
    private  int i=5;
    ProgressDialog xh_pDialog;

    private MessageAdapter adapter;
    private ArrayList<Storeditem> storeditems = new ArrayList<>();

    private String SoftVersion;
    private String DataServerIP;
    private String Key;
    private String DataServerPort;
    private String SoftName;
    private String mDeviceid;
    private String mUsercode;
    private String mUserpwd;
    private String mVersion;
    private String mHospitalid;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_inform;
    }

    @Override
    protected void initViews() {


        SharedPreferences sPreferences=getSharedPreferences("muser", MODE_PRIVATE);
        Key=sPreferences.getString("Key", "");
        DataServerIP=sPreferences.getString("DataServerIP", "");
        DataServerPort=sPreferences.getString("DataServerPort", "");
        mDeviceid=sPreferences.getString("mDeviceid", "");
        mUsercode=sPreferences.getString("mUsercode", "");
        mUserpwd=sPreferences.getString("mUserpwd", "");
        mVersion=sPreferences.getString("mVersion", "");
        mHospitalid=sPreferences.getString("mHospitalid", "");

        userFeedbackGoback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        if (!Utils.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        QueryAddressTask queryAddressTask = new QueryAddressTask();
        queryAddressTask.execute(Honst, time,  i+"");
        adapter  = new MessageAdapter(mContext, storeditems);
        /*rvInvest1.setLayoutManager(new LinearLayoutManager(mContext));
        rvInvest1.setAdapter(adapter);*/

        rvInvest1.setAdapter(adapter);
        rvInvest1.setGroupIndicator(null);

    }




    class QueryAddressTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            xh_pDialog = new ProgressDialog(mContext);

            // 设置进度条风格，风格为圆形，旋转的
            xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            xh_pDialog.setTitle("正在加载，请稍等");
            xh_pDialog.setIndeterminate(false);

            // 设置ProgressDialog 是否可以按退回键取消
            xh_pDialog.setCancelable(true);

            // 让ProgressDialog显示
            xh_pDialog.show();

        }
        protected String doInBackground(String... params) {
            // 查询手机号码（段）信息*/
            String    result = null;

            try {
                result = getData(params[0]);


            } catch (Exception e) {

                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法

            Log.e("ADDADADggg",result);
            return result;
        }



        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            // 将WebService返回的结果显示在TextView中

            xh_pDialog.dismiss();
            if (result != null) {
                XStream xStream1 = new EncodeXstream("1.0", "gb2312");
                xStream1.alias("result", Data.class);
                xStream1.useAttributeFor(Param1.class, "size");
                xStream1.addImplicitCollection(Param1.class, "storeditems");
                xStream1.alias("storeditem", Storeditem.class);
                Data data1 = (Data) xStream1.fromXML(result);

                Log.e("TAG11", "status: " + data1.getStatus());
                Log.e("TAG11", "errorinfo: " + data1.getErrorinfo());
                Log.e("TAG11","successinfo"+data1.getSuccessinfo());
                Log.e("TAG11", "param1 size: " + data1.getSuccessinfo().getParam1().getSize());

                Log.e("aadasf",result);

                try {

                    storeditems.clear();
                    storeditems.addAll((ArrayList<Storeditem>) data1.getSuccessinfo().getParam1().getStoreditems());
                    adapter.notifyDataSetChanged();



                } catch (Exception e) {

                    e.printStackTrace();
                }

            }else {

                ToastUtil.toast(mContext,"网络异常,请检查!");
            }


        }
    }
    private String getData(String param){
        String    result = null;
        String WSDL_URI = "http://"+DataServerIP+":"+DataServerPort+"/soap/IHyWebServer";//wsdl 的uri
        Log.d("FAFAFF",WSDL_URI);
        String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
        String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

        SoapObject request = new SoapObject(namespace, methodName);

        String de = "<hywebserviceroot>" +
                "<funname>GetMbUserFunction</funname>" +
                "<hospitalid>"+mHospitalid+"</hospitalid>" +
                "    <key>"+Key+"</key>" +
                "    <deviceid>"+mDeviceid+"</deviceid>" +
                "    <usercode>"+mUsercode+"</usercode>" +
                "    <userpwd>"+mUserpwd+"</userpwd>" +
                "    <version>"+mVersion+"</version>" +
                "    <params>" +
                "     <param1><sFunName>GetSYXX</sFunName></param1>" +
                "     <param2></param2>" +
                "    </params>" +
                "</hywebserviceroot>";

        request.addProperty("aXml", de);
        //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
            envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
            envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
            HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
            httpTransportSE.debug = false;
            httpTransportSE.call("urn:HyWebServerIntf-IHyWebServer#HyWebServiceIntfMethod", envelope);//调用

            // 获取服务器响应返回的SOAP消息
            SoapObject object = (SoapObject) envelope.bodyIn;
            result = object.getProperty(0).toString();
            //     Log.e("DSDSDS", result);
            return result;

        } catch (Exception e) {
            Log.e("TAG", "getData: "+e );
        }
        return result;

    }


    private  class  MessageAdapter extends BaseExpandableListAdapter {


        private Context context;
        private ArrayList<Storeditem> storeditems;

        public MessageAdapter(Context context, ArrayList<Storeditem> dataLists) {
            this.context = context;
            this.storeditems = dataLists;
        }

        public Object getChild(int groupPosition, int childPosition) {
            return storeditems.get(groupPosition);
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            ViewHolder1 viewHolder1;
            if (convertView == null) {
                viewHolder1 = new ViewHolder1();
                convertView = View.inflate(context, R.layout.activity_reaws_item2, null);
                viewHolder1.tv = (TextView) convertView.findViewById(R.id.activity_home2);


                convertView.setTag(viewHolder1);
            } else {
                viewHolder1 = (ViewHolder1) convertView.getTag();
            }
            viewHolder1.tv.setText(storeditems.get(groupPosition).getsFSXX());

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }


        public Object getGroup(int groupPosition) {
            return storeditems.get(groupPosition);
        }

        public int getGroupCount() {
            return storeditems.size();
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(context, R.layout.activity_reaws_item1, null);
                viewHolder.tv = (TextView) convertView.findViewById(R.id.activity_home);
                viewHolder.tv1 = (TextView) convertView.findViewById(R.id.activity_home1);

                convertView.setTag(viewHolder);
                viewHolder.tv.setText(storeditems.get(groupPosition).getsXXLX());
                viewHolder.tv1.setText("发布日期："+storeditems.get(groupPosition).getdFSSJ());
            }
            return convertView;
        }


        class ViewHolder {
            TextView tv;
            TextView tv1;

        }

        class ViewHolder1 {
            TextView tv;
            TextView tv1;
            TextView tv2;
        }
    }
    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (xh_pDialog != null){
            xh_pDialog.dismiss();
            xh_pDialog = null;
        }
    }
    @Override
    protected void onError_(Throwable e) {

    }

    @Override
    protected void onCancel_() {

    }

}
